package com.impetus.project.skilltest.client.pages;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.impetus.project.skilltest.client.stub.SecurityService;
import com.impetus.project.skilltest.client.stub.SecurityServiceAsync;

public class TopMenu {
	
	private static final SecurityServiceAsync securityService = GWT.create(SecurityService.class);
	
	public static HorizontalPanel drawMenu(final PageData pageData)
	{
		HorizontalPanel hpanel = new HorizontalPanel();
		
		Button button = new Button("Home");
		button.setTitle("Test Listing");
		button.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				PageRouter.loadPage(GUIConstants.PAGES.HOME_PAGE, pageData);
			}
		});
		hpanel.add(button);
		
		if(pageData.getUser().getIsAdmin()){
			button = new Button("Schedule Test");
			button.setTitle("Schedule Test");
			button.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					PageRouter.loadPage(GUIConstants.PAGES.TEST_EDIT_PAGE, pageData);
				}
			});
			hpanel.add(button);
		}
		
		button = new Button("Logout");
		button.setTitle("Logout");
		button.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				securityService.logout(pageData.getUser(), new AsyncCallback<Void>(){
					public void onFailure(Throwable t) {
						pageData.setExceptionCaught(t);
						PageRouter.loadPage(GUIConstants.PAGES.ERROR_PAGE, pageData);
					}
					public void onSuccess(Void result) {
						PageRouter.loadPage(GUIConstants.PAGES.LOGIN_PAGE, pageData);
					}
				});
			}
		});
		hpanel.add(button);
		
		return hpanel;
	}
}
